package com.fan.chat.component.context;

import com.plexpt.chatgpt.entity.chat.Message;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class LocalChatContextStrategy implements ChatContextStrategy {

    private static final Map<String, List<Message>> contextMap = new HashMap<>();

    private static final Map<String, Long> contextExpireMap = new HashMap<>();

    private static long lastClearExpireTime = System.currentTimeMillis();

    private static final long contextExpireTime = 60 * 1000;

    @Override
    public List<Message> getListMessage(String id) {
        return contextMap.get(id);
    }

    @Override
    public void addMessage(String id, List<Message> messages) {
        contextMap.put(id, messages);
        long curTime = System.currentTimeMillis();
        contextExpireMap.put(id, curTime);
        long expireTime = curTime - contextExpireTime;
        if (lastClearExpireTime > expireTime) {
            clear(id, expireTime);
            lastClearExpireTime = curTime;
        }
    }

    private void clear(String id, long expireTime) {
        Set<String> contextExpireKeys = contextExpireMap.keySet();
        for (String contextExpireKey : contextExpireKeys) {
            Long addTime = contextExpireMap.get(contextExpireKey);
            if (addTime < expireTime) {
                remove(id);
            }
        }
    }

    @Override
    public void remove(String id) {
        contextMap.remove(id);
        contextExpireMap.remove(id);
    }

}
